package com.bes.aiProject.service.impl;

import com.bes.aiProject.config.MyUtils;
import com.bes.aiProject.entry.SxAAbnormalResult;
import com.bes.aiProject.entry.SxAAnalyzeResultTemp;
import com.bes.aiProject.entry.SxMBusinessProcessConf;
import com.bes.aiProject.mapper.SxAAbnormalResultMapper;
import com.bes.aiProject.mapper.SxAAnalyzeResultTempMapper;
import com.bes.aiProject.mapper.SxMBusinessProcessConfMapper;
import com.bes.aiProject.service.AIService;
import com.bes.aiProject.service.ModelPredictService;
import com.bes.aiProject.service.ModelTrainService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ModelTrainServiceImpl implements ModelTrainService {
    Gson gson = new Gson();
    @Value("${task.group-condition}")
    private String conditions;
    @Autowired
    private SxMBusinessProcessConfMapper processConfMapper;
    @Autowired
    SxAAbnormalResultMapper resultMapper;
    @Autowired
    AIService aiService;
    @Autowired
    SxAAnalyzeResultTempMapper analyzeResultTempMapper;
    @Autowired
    ModelPredictService modelPredictService;


    @Override
    public void ModelTrain() {

        List<String> reverseConditionList = new ArrayList<>(Arrays.asList(conditions.split(",")));
        List<String> queryConditionArray = new ArrayList<>(reverseConditionList);
        Collections.reverse(reverseConditionList);
        for (int i = 0; i < reverseConditionList.size(); i++) {
            if (i == 0) {//处理叶子节点
                String leafCondition = MyUtils.ConditionMap.get(reverseConditionList.get(i)).get(0);
                List<SxAAbnormalResult> abnormalConditionGroups = resultMapper.getAbnormalConditionGroup(MyUtils.getGroupConditions(queryConditionArray));
                if (CollectionUtils.isEmpty(abnormalConditionGroups)) {
                    log.info("模型训练查询异常检测结果表为空，无可训练数据！");
                }
                //校验指标数据是否满足并训练模型
                for (SxAAbnormalResult currentGroup : abnormalConditionGroups) {

                    List<SxMBusinessProcessConf> currentMetricLimit = processConfMapper.getLeafMetricList(leafCondition, currentGroup.getEnterpriseCode(), currentGroup.getBusinessCode(), currentGroup.getTaskCode());
                    List<SxAAbnormalResult> currentMetricScore = resultMapper.getScoreByGroup(currentGroup.getAreaCode(), currentGroup.getCustomerType(), currentGroup.getEnterpriseCode(), currentGroup.getBusinessCode(), currentGroup.getTaskCode());
                    //当前模型要求的指标
                    List<String> MetricLimit = currentMetricLimit.stream().map(SxMBusinessProcessConf::getMetricCode).distinct().collect(Collectors.toList());
                    //当前模型具有的指标
                    List<String> abnormalMetricList = currentMetricScore.stream().map(SxAAbnormalResult::getMetricCode).distinct().collect(Collectors.toList());
                    MetricLimit.removeAll(abnormalMetricList);
                    if (!CollectionUtils.isEmpty(MetricLimit)) {
                        log.info("模型训练指标类型不足");
                        continue;
                    }
                    //去掉多余指标
                    currentMetricScore = currentMetricScore.stream().filter(x -> MetricLimit.contains(x.getMetricCode())).collect(Collectors.toList());
                    //开始训练模型
                    aiService.trainLeafModel(currentMetricScore, queryConditionArray, currentGroup);
                    //训练完成需要预测上一次数据
                    //先检查是否存在预测过的数据
                    List<SxAAnalyzeResultTemp> aAnalyzeResultTemps = analyzeResultTempMapper.getAnalyzeResultTemp(currentGroup.getAreaCode(), currentGroup.getCustomerType(), currentGroup.getEnterpriseCode(), currentGroup.getBusinessCode(), currentGroup.getTaskCode());
                    if (CollectionUtils.isEmpty(aAnalyzeResultTemps)) { //第一次训练模型，没有数据立刻触发预测
                        modelPredictService.ModelPredictMetric(currentMetricScore, queryConditionArray, currentGroup);
                    }
                }
            } else {//处理正常节点

            }
            //训练完成需要预测上一次数据


            //最多汇聚到商业过程级别
            queryConditionArray.remove(queryConditionArray.size() - 1);
            if ("商业过程".equals(reverseConditionList.get(i))) break;
        }


    }
}
